import React, { useState, useEffect } from 'react';
import { useAuth } from '@/hooks/contexts/AuthContext';
import styles from './favorites.module.css';
import Icon from '@/components/icon/Icon';
import type { IconPrefix, IconName } from '@fortawesome/fontawesome-svg-core';
import Link from 'next/link';

// 收藏项类型定义
interface FavoriteItem {
    id: string;
    title: string;
    description: string;
    icon: string;
    createdAt: string;
    diagramId: string;
    category: string;
}

export default function Favorites() {
    const {  } = useAuth();

    // 模拟收藏数据
    const favoriteItems: FavoriteItem[] = [
        {
            id: '1',
            title: '铜价暴涨幕后推手',
            description: '谁在炒作全球铜价？',
            icon: 'chart-line',
            createdAt: '2024-06-10',
            diagramId: 'copper-price-surge',
            category: '大宗商品'
        },
        {
            id: '2',
            title: '小米汽车颠覆市场？',
            description: 'SU7上市首月订单破10万',
            icon: 'car',
            createdAt: '2024-06-05',
            diagramId: 'xiaomi-auto-impact',
            category: '新能源汽车'
        },
        {
            id: '3',
            title: '粮食危机警报',
            description: '极端天气致全球减产30%',
            icon: 'wheat-awn',
            createdAt: '2024-05-28',
            diagramId: 'food-crisis-alert',
            category: '农产品'
        },
        {
            id: '4',
            title: '美联储加息杀手锏',
            description: '全球资本回流美国',
            icon: 'dollar-sign', 
            createdAt: '2024-05-20',
            diagramId: 'fed-rate-hike',
            category: '宏观经济'
        },
        {
            id: '5',
            title: '电池技术终极对决',
            description: '固态电池VS磷酸铁锂',
            icon: 'battery-full',
            createdAt: '2024-05-15',
            diagramId: 'battery-tech-battle',
            category: '新能源汽车'
        },
        {
            id: '6',
            title: '稀土管制升级',
            description: '全球供应链震荡',
            icon: 'chart-pie', 
            createdAt: '2024-05-10',
            diagramId: 'rare-earth-controls',
            category: '大宗商品'
        }
    ];



    // 状态管理
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [filteredItems, setFilteredItems] = useState<FavoriteItem[]>([]);

    // 获取所有唯一分类
    const allCategories = ['all', ...Array.from(new Set(favoriteItems.map(item => item.category)))];

    // 格式化日期
    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        }).format(date);
    };

    // 处理搜索和筛选
    useEffect(() => {
        let result = [...favoriteItems];

        // 应用分类筛选
        if (selectedCategory !== 'all') {
            result = result.filter(item => item.category === selectedCategory);
        }

        // 应用搜索筛选
        if (searchTerm) {
            const term = searchTerm.toLowerCase();
            result = result.filter(
                item => item.title.toLowerCase().includes(term) ||
                    item.description.toLowerCase().includes(term)
            );
        }

        setFilteredItems(result);
    }, [searchTerm, selectedCategory]);

    // 判断是否需要显示结果统计：只有当有搜索词或选择了特定分类时才显示
    const shouldShowResultsCount = searchTerm !== '' || selectedCategory !== 'all';

    return (
        <div className={styles['favorites-container']}>
            <div className={styles['section-header']}>
                <h2>我的收藏</h2>
                <p>查看和管理您收藏的知识图谱内容</p>
            </div>

            {/* 搜索和筛选区域 */}
            <div className={styles['search-filter-container']}>
                <div className={styles['search-box']}>
                    <Icon icon={['fas', 'search'] as [IconPrefix, IconName]} className={styles['search-icon']} />
                    <input
                        type="text"
                        placeholder="搜索收藏内容..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className={styles['search-input']}
                    />
                    {searchTerm && (
                        <button
                            className={styles['clear-search']}
                            onClick={() => setSearchTerm('')}
                        >
                            <Icon icon={['fas', 'times'] as [IconPrefix, IconName]} />
                        </button>
                    )}
                </div>

                <div className={styles['filter-dropdown']}>
                    <select
                        value={selectedCategory}
                        onChange={(e) => setSelectedCategory(e.target.value)}
                        className={styles['filter-select']}
                    >
                        {allCategories.map(category => (
                            <option key={category} value={category}>
                                {category === 'all' ? '全部分类' : category}
                            </option>
                        ))}
                    </select>
                </div>
            </div>

            {/* 结果统计 - 仅在有搜索或筛选时显示 */}
            {shouldShowResultsCount && filteredItems.length > 0 && (
                <div className={styles['results-count']}>
                    找到 <span className={styles['count-highlight']}>{filteredItems.length}</span> 个结果
                    {selectedCategory !== 'all' && searchTerm && (
                        <span>，筛选条件：{selectedCategory}、&#34;{searchTerm}&#34;</span>
                    )}
                    {selectedCategory !== 'all' && !searchTerm && (
                        <span>，筛选条件：{selectedCategory}</span>
                    )}
                    {selectedCategory === 'all' && searchTerm && (
                        <span>，搜索：&#34;{searchTerm}&#34;</span>
                    )}
                </div>
            )}

            {filteredItems.length === 0 ? (
                <div className={styles['empty-favorites']}>
                    <Icon icon={['far', 'heart'] as [IconPrefix, IconName]} className={styles['empty-icon']} />
                    <p>
                        {searchTerm || selectedCategory !== 'all'
                            ? '没有找到符合条件的收藏内容，请尝试其他搜索词或筛选条件。'
                            : '您还没有收藏任何内容，开始探索并收藏您感兴趣的知识图谱吧！'
                        }
                    </p>
                    <Link href="/" className={styles['explore-btn']}>
                        <span>探索知识图谱</span>
                    </Link>
                </div>
            ) : (
                <div className={styles['favorites-grid']}>
                    {filteredItems.map((item) => (
                        <div key={item.id} className={styles['favorite-card']}>
                            <div className={styles['favorite-category']}>{item.category}</div>
                            <div className={styles['favorite-icon']}>
                                <Icon icon={['fas', item.icon] as [IconPrefix, IconName]} />
                            </div>
                            <div className={styles['favorite-info']}>
                                <h3 className={styles['favorite-title']}>{item.title}</h3>
                                <p className={styles['favorite-desc']}>{item.description}</p>
                                <div className={styles['favorite-meta']}>
                                    <span className={styles['favorite-date']}>{formatDate(item.createdAt)}</span>
                                    <Link
                                        href={`/diagram/${item.diagramId}`}
                                        className={styles['view-diagram-btn']}
                                    >
                                        <span>查看图谱</span>
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
    